package com.khaliil.kkadmin.demo.sse;

import com.khalil.kkadmin.common.util.IdTool;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.*;

@RestController
@RequestMapping("/demoSse")
public class SseController {


    @GetMapping(value = "/mvcSse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter mvcSse() {
        SpringMvcSseService springMvcSseService = new SpringMvcSseService();
        SseEmitter sseEmitter = springMvcSseService.createSseEmitter();
        String eventId = IdTool.uuid();
        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    TimeUnit.SECONDS.sleep(1);
                    sseEmitter.send(SseEmitter.event().id(eventId).data(new Date().toString()).build());
                }
                sseEmitter.send(SseEmitter.event().id(eventId).data("[DONE]").build());
                sseEmitter.complete();
            } catch (IOException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        return sseEmitter;
    }
}
